package com.corgi.test.cglib;

import com.corgi.test.cglib.copier.bean.User;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CglibEnhancer
 *
 * @title: CglibEnhancer
 * @description:
 * @author: dengmiao
 * @create: 2019-12-20 16:30
 **/
public class CglibEnhancer implements MethodInterceptor {

    public Object getProxy(Class clazz){
        //设置需要创建子类的类
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);//设置回调函数
        //通过字节码技术动态创建子类实例
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("--前置代理");
        Object result = methodProxy.invokeSuper(o, objects);
        System.out.println("---后置代理");
        return result;
    }

    public static void main(String[] args) {
        CglibEnhancer enhancer = new CglibEnhancer();
        Object proxy = enhancer.getProxy(User.class);
        System.out.println(proxy instanceof User);
        User user = (User) proxy;
        System.out.println(user.getId());
    }
}
